package com.acme.chat.message;

import java.io.Serializable;

/**
 * Class represents message object by which server and client exchange info.
 */
public class ChatMessage extends AbstractMessage implements Serializable {

    /**
     * Create Message with specified type and string without trailing spaces.
     *
     * @param type
     * @param message
     */
    public ChatMessage(final MessageType type, final String message, String nameToWho, final String room) {
        this.type = type;
        this.message = deleteTrailingSpaces(message);
        if (nameToWho != null) {
            nameToWho = nameToWho.trim();
        }
        this.nameToWho = nameToWho;
        this.room=room;
    }

    /**
     * Create Message with type and empty string.
     *
     * @param type
     */
    public ChatMessage(MessageType type) {
        this(type, "", "", null);
    }

    /**
     * Create Message with type.
     *
     * @param type
     */
    public ChatMessage(MessageType type, final String message) {
        this(type, message, "", null);
    }

    /**
     * Method deletes trailing spaces from the string.
     *
     * @param messageText
     * @return String
     */
    private String deleteTrailingSpaces(String messageText) {
        StringBuilder messageTextSB = new StringBuilder(messageText);
        for (int i = messageText.length() - 1; i >= 0; i--) {
            if (Character.isWhitespace(messageTextSB.charAt(i))) {
                messageTextSB.deleteCharAt(i);
            } else {
                break;
            }
        }
        messageTextSB.append("\n");
        return messageTextSB.toString();
    }
}
